package cn.dwj.hadoop.mr.areapartition;

import cn.dwj.hadoop.mr.flowsum.FlowBean;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 * Created by Administrator on 2017/12/27 0027.
 * 对原始日志进行流量统计，将不同省份的用户统计结果输出到不同文件
 * 需要改造两个机制
 * 1、改造分区的逻辑，自定义一个partitioner
 * 2、自定义reduce task并发任务数
 */
public class FlowSumArea {
    public static class FlowSumAreaMapper extends Mapper<LongWritable, Text, Text, FlowBean>{
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String line = value.toString();
            String[] str = StringUtils.split(line, "\t");

            String phoneNB = str[1];
            long uFlow = Long.parseLong(str[7]);
            long dFlow = Long.parseLong(str[8]);

            context.write(new Text(phoneNB), new FlowBean(phoneNB, uFlow, dFlow));
        }
    }

    public static class FlowSumAreaReduce extends Reducer<Text, FlowBean, Text, FlowBean>{
        @Override
        protected void reduce(Text key, Iterable<FlowBean> values, Context context) throws IOException, InterruptedException {
            long upFlowCount = 0;
            long dFlowCount = 0;
            for(FlowBean bean : values){
                upFlowCount = upFlowCount + bean.getUpFlow();
                dFlowCount = dFlowCount + bean.getdFlow();
            }

            context.write(key, new FlowBean(key.toString(), upFlowCount, dFlowCount));
        }
    }

    public static void main(String[] args) throws Exception {
        System.setProperty("hadoop.home.dir","E:/project/study/hadoop-2.6.5");
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf);
        //设置整个job所在的那些类在哪个jar包中
        job.setJarByClass(FlowSumArea.class);
        //本job使用的map和reduce的类
        job.setMapperClass(FlowSumAreaMapper.class);
        job.setReducerClass(FlowSumAreaReduce.class);

        //设置逻辑分组的定义
        job.setPartitionerClass(AreaPartitioner.class);

        //指定输出数据的类型，对mapper和reduce的类型都起作用
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(FlowBean.class);

        //设置reduce的任务并发数，应该跟分组的数量保持一致
        job.setNumReduceTasks(6);

        FileInputFormat.setInputPaths(job, new Path[]{new Path("E:/hadoop/flowarea/input/")});
        FileOutputFormat.setOutputPath(job, new Path("E:/hadoop/flowarea/output/"));//指定处理结果输出数据存放在路径

        System.exit(job.waitForCompletion(true)?0:1);
    }
}
